'use strict';

var argv = require('optimist').argv;
var prompt = require('prompt');

function run(opts) {
  var passwordUtil = require('../lib/password')(opts);
  var encrypt = passwordUtil.encrypt;

  if (argv.help) {
    console.info('./passwordUtil --password <password to encrypt>');
    console.info('./passwordUtil --split <password to split> [--filePrefix prefix]');
  } else if (argv.split) {
    if (typeof argv.split === 'string') {
      var shares = passwordUtil.splitPwd(argv.split, argv.filePrefix);
      console.info('Shares are(' + shares + ')');
    } else {
      prompt.message = 'Please enter';
      prompt.delimiter = ' ';
      prompt.override = argv;
      prompt.start();
      prompt.get({
        properties: {
          passwordToSplit: {
            description: 'password to split',
            hidden: true
          },
          filePrefix: {
            description: 'File prefix or blank to skip file creation',
            hidden: false
          }
        }
      }, function (err, result) {
        var shares = passwordUtil.splitPwd(result.passwordToSplit, result.filePrefix);
        console.info('Shares are(' + shares + ')');
      });
    }
  } else {
    prompt.message = 'Please enter';
    prompt.delimiter = ' ';

    prompt.override = argv;
    prompt.start();

    prompt.get({
      properties: {
        password: {
          description: 'password to encrypt',
          hidden: true
        }
      }
    }, function (err, result) {
      var encryptedPassword = encrypt(result.password, opts ? opts.keyfile : undefined);
      console.info('Encrypted password is enc(' + encryptedPassword + ')');
    });
  }
}

module.exports = function(opts) {
  run(opts);
}
